package it.gestionedocumentale.struts.action;

import it.gestionedocumentale.model.Utente;
import it.gestionedocumentale.spring.service.MyServiceFactory;
import it.gestionedocumentale.struts.form.LoginForm;
import it.gestionedocumentale.utility.UtilityDate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class LoginAction extends Action{
	
	private static Log log = LogFactory.getLog(LoginAction.class);
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		LoginForm form2 = (LoginForm) form;
		Utente utenteSession = null;
		try {
			utenteSession = MyServiceFactory.getUtenteService().findByLoginAndPassword(form2.getLogin(), form2.getPassword());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			return mapping.findForward("error");
		}
		
		if(utenteSession == null) {
			
			// log da verificare
			String clientIP = request.getRemoteAddr();
			
			String dataTentativoAccesso = new String();
				dataTentativoAccesso = UtilityDate.getDateAsString(UtilityDate.today(), "dd/MM/yyyy HH:mm:ss.SSS");
			
			log.info("Tentativo di accesso da: "+ clientIP + "\n in data: "+dataTentativoAccesso);
			return mapping.findForward("loginWrong");
		}
		
		// data di accesso
		
		String dataAccesso = new String();
			dataAccesso = UtilityDate.getDateAsString(UtilityDate.today(), "dd/MM/yyyy HH:mm:ss.SSS");
		
		log.info("Utente loggato come: "+ utenteSession +"\n in data: "+ dataAccesso);
		
		request.getSession().setAttribute("utenteSession", utenteSession);
		
		return mapping.findForward("loginOk");
	}
}
